const app = getApp();
const pageSize = 15;
const cardTypes = [{
  value: "",
  name: "全部"
}, {
  value: "1",
  name: "特殊卡"
}, {
  value: "2",
  name: "普通卡"
}];
const cardStatuses = [{
  value: "",
  name: "全部"
}, {
  value: "1",
  name: "正常"
}, {
  value: "2",
  name: "挂失"
}]
Page({
  data: {
    conditions: { //存放搜索条件
      user_keyword: "",
      start_money: "",
      end_money: "",
      cardTypeIndex: "",
      cardStatusIndex: "",
    },
    cardTypes, //水卡类型
    cardStatuses, //水卡状态
    isFilter: false, //搜索高亮
    drawer: false, //搜索抽屉
    menuIndex: "", //展开更多菜单的列表项
    modelshow: true,
    modelstate: '', // 1解绑 2挂失 3解挂
    list: [],
    total: 0, //总条数
    nomore: false, //列表结束nomore
    loadmore: false, //列表更多loadmore
    empty: false, //空数据
    cardIndex: '', //操作数据的序号
    isModalClear: false, //置0弹窗
    modalClearContent: "", //置0弹窗文字
    balance: "",
    bind_phone: "",
    isModalInput: false,
    showInput: false,
    franchisees: false, //区别是否为加盟商
    isModalSysn: false,
    modalSysnContent: `确认同步水卡余额？`
  },

  onPullDownRefresh: function () {
    this.reloadData();
  },

  /**
   * 生命周期函数--监听页面加载 is_special 1特殊 2普通 
   */
  onLoad: function (options) {
    if (options && options.type) {
      this.type = options.type;
      this.setData({
        franchisees: true
      })
    }
    var conditions = this.data.conditions;
    conditions.cardTypeIndex = options.is_special ? Number(options.is_special) : "";
    this.setData({
      conditions
    });
    if (options.is_special == 1) {
      wx.setNavigationBarTitle({
        title: '我的水卡(特殊水卡)',
      })
    } else {
      wx.setNavigationBarTitle({
        title: '我的水卡',
      })
    }
    wx.showLoading();
    this.page = 1;
    this.getCardList();
  },


  reloadData() {
    this.page = 1;
    this.setData({
      loadmore: false,
      nomore: false,
      list: [],
      total: 0,
    })
    wx.showLoading()
    this.getCardList();
  },


  showDrawer() {
    this.condition = {
      ...this.data.conditions
    };
    this.setData({
      drawer: true,
    })
  },

  closeDrawer() {
    this.setData({
      drawer: false,
      conditions: this.condition
    })
    delete(this.condition)
  },

  resetDrawer() {
    const conditions = this.data.conditions;
    for (let x in conditions) {
      conditions[x] = "";
    }
    this.setData({
      conditions,
    })
    wx.setNavigationBarTitle({
      title: '我的水卡',
    })
  },
  confirmDrawer() {
    let isFilter = false;
    const conditions = this.data.conditions;
    for (let x in conditions) {
      conditions[x] !== "" && (isFilter = true);
    }
    this.setData({
      isFilter
    })
    delete(this.condition);
    this.reloadData();
  },


  handleMore(e) {
    this.setData({
      menuIndex: e.currentTarget.dataset.index
    })
  },

  closeMenu() {
    this.setData({
      menuIndex: ""
    })
  },

  handleInput(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [`conditions.${name}`]: e.detail.value
    })
  },

  handleChange(e) {
    const {
      index,
      name
    } = e.currentTarget.dataset;
    this.setData({
      [`conditions.${name}`]: index
    })
  },



  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.loadmore) {
      ++this.page;
      this.getCardList();
    }
  },
  // 解绑
  Untie: function (e) {
    let card = e.currentTarget.dataset.card;
    let cardIndex = e.currentTarget.dataset.cardindex;
    this.setData({
      modelshow: false,
      modelstate: 1,
      cardIndex: cardIndex
    })
  },
  // 挂失
  reloss: function (e) {
    //console.log(e);
    let card = e.currentTarget.dataset.card;
    let cardIndex = e.currentTarget.dataset.cardindex;
    this.setData({
      modelshow: false,
      modelstate: 2,
      cardIndex: cardIndex
    })
  },
  // 解挂
  hangout: function (e) {
    let card = e.currentTarget.dataset.card;
    let cardIndex = e.currentTarget.dataset.cardindex;
    this.setData({
      modelshow: false,
      modelstate: 3,
      cardIndex: cardIndex
    })
  },
  //补卡
  supplementCard(e) {
    let card = e.currentTarget.dataset.card;
    let cardIndex = e.currentTarget.dataset.cardindex;
    this.setData({
      cardIndex: cardIndex
    })
    wx.navigateTo({
      url: `../supplementCard/supplementCard?card=${e.currentTarget.dataset.card.card}&type=${this.data.franchisees?1:''}`,
    })
  },
  // 关闭弹窗
  closemodel: function () {
    this.setData({
      modelshow: true
    })
  },

  //获取电子卡列表
  getCardList() {
    const conditions = this.data.conditions;
    const param = {
      page: this.page,
      row: pageSize,
      user_keyword: conditions.user_keyword,
      start_money: conditions.start_money,
      end_money: conditions.end_money,
      card_status: conditions.cardStatusIndex !== "" ? this.data.cardStatuses[conditions.cardStatusIndex].value : '',
      is_special: conditions.cardTypeIndex !== "" ? this.data.cardTypes[conditions.cardTypeIndex].value : "",
    }
    if (conditions.cardTypeIndex == 1 || conditions.cardTypeIndex == 2) {
      wx.setNavigationBarTitle({
        title: conditions.cardTypeIndex == 1 ? '我的水卡(特殊水卡)' : '我的水卡',
      })
    } else {
      wx.setNavigationBarTitle({
        title: '我的水卡',
      })
    }
    this.type && (param.type = this.type);
    app.ajax({
      url: 'Partner/WaterCard/waterCardList',
      data: param,
      success: res => {
        wx.hideLoading();
        wx.stopPullDownRefresh()
        if (res.data.code == 1000) {
          const source = res.data.data;
          let list = this.page == 1 ? source.data : this.data.list.concat(source.data);
          let total = source.page.total_number;
          this.setData({
            empty: total == 0 ? true : false,
            total,
            list,
            nomore: list.length >= total ? true : false,
            loadmore: list.length < total ? true : false,
            drawer: false
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: err => {
        wx.hideLoading();
        wx.stopPullDownRefresh();
        app.showToast("网络错误")
      }
    })
  },


  //确认操作
  okmodel(e) {
    var that = this;
    let type = e.currentTarget.dataset.type;
    that.closemodel();
    //确认解绑
    if (type == 1) {
      app.ajax({
        url: 'Partner/WaterCard/unbind',
        data: {
          sn: that.data.list[that.data.cardIndex].real_card
        },
        success: function (res) {
          //console.log(res)
          if (res.data.code == 1000) {
            that.reloadData();
            app.showToast('已成功解除绑定');
          } else {
            app.showToast(res.data.message);
          }
        }
      })
    } else if (type == 2) { //确认挂失
      app.ajax({
        url: 'Partner/WaterCard/reportLoss',
        data: {
          id: that.data.list[that.data.cardIndex].water_id
        },
        success: function (res) {
          //console.log(res)
          if (res.data.code == 1000) {
            that.reloadData();
            app.showToast('已成功挂失');
          } else {
            app.showToast(res.data.message);
          }
        }
      })
    } else if (type == 3) { //确认解挂
      app.ajax({
        url: 'Partner/WaterCard/unReportLoss',
        data: {
          id: that.data.list[that.data.cardIndex].water_id
        },
        success: function (res) {
          //console.log(res)
          if (res.data.code == 1000) {
            that.reloadData();
            app.showToast('已成功解挂');
          } else {
            app.showToast(res.data.message);
          }
        }
      })
    }
  },

  hideClear() {
    this.setData({
      isModalClear: false
    })
    delete(this.water_id);
    delete(this.selectIndex)
  },

  handleClear(e) {
    const index = e.detail.index;
    if (index == 0) {
      this.hideClear()
    } else {
      if (this.submit) {
        app.showToast("正在处理中...");
        return false
      }
      this.submit = true;
      app.ajax({
        url: "Partner/WaterCard/cardBalanceUpdate",
        data: {
          id: this.water_id,
          type: 2
        },
        success: res => {
          delete(this.submit);
          if (res.data.code == 1000) {
            app.showToast(res.data.message, "success");
            this.setData({
              [`list[${this.selectIndex}].balance`]: "0.000"
            })
          } else {
            app.showToast(res.data.message)
          }
          this.hideClear();
        },
        error: e => {
          delete(this.submit);
          app.showToast("请求失败")
        }
      })
    }
  },


  showModalClear(e) {
    const data = e.currentTarget.dataset;
    this.water_id = data.id;
    this.selectIndex = data.index;
    this.setData({
      isModalClear: true,
      modalClearContent: `确认将${data.name && `用户【${data.name}】`}该水卡清零？`
    })
  },
  hideSysn() {
    this.setData({
      isModalSysn: false
    })
    delete(this.water_id);
    delete(this.selectIndex)
  },

  handleSysn(e) {
    const index = e.detail.index;
    if (index == 0) {
      this.hideSysn();
    } else {
      if (this.submit) {
        app.showToast("正在处理中...");
        return false
      }
      this.submit = true;
      app.ajax({
        url: "Common/Card/syncCardBalance",
        data: {
          water_id: this.water_id,
        },
        success: res => {
          delete(this.submit);
          app.showToast(res.data.message);
          this.hideSysn();
        },
        error: e => {
          delete(this.submit);
          app.showToast("请求失败")
        }
      })
    }
  },

  showModalSysn(e) {
    const data = e.currentTarget.dataset;
    this.water_id = data.id;
    this.selectIndex = data.index;
    this.setData({
      isModalSysn: true,
      modalSysnContent: `确认同步水卡余额？`
    })
  },

  alterBalance() {
    if (this.sub == true) {
      app.showToast("正在处理中...");
      return false;
    }
    this.sub = true;
    app.ajax({
      url: "Partner/WaterCard/cardBalanceUpdate",
      data: {
        id: this.water_id,
        to_money: this.data.balance,
        type: 1
      },
      success: res => {
        delete(this.sub);
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          this.setData({
            [`list[${this.alterIndex}].balance`]: parseFloat(this.data.balance).toFixed(3)
          })
        } else {
          app.showToast(res.data.message);
        }
        this.hideModalInput();
      },
      error: e => {
        delete(this.sub)
      }
    })
  },
  alterPhone() {
    if (this.sub == true) {
      app.showToast("正在处理中...");
      return false;
    }
    this.sub = true;
    app.ajax({
      url: "Partner/WaterCard/updateUserPhone",
      data: {
        card_id: this.water_id,
        phone: this.data.bind_phone
      },
      success: res => {
        delete(this.sub);
        if (res.data.code == 1000) {
          app.showToast(res.data.message, "success");
          this.setData({
            [`list[${this.alterIndex}].bind_phone`]: this.data.bind_phone
          })
        } else {
          app.showToast(res.data.message);
        }
        this.hideModalPhone();
      },
      error: e => {
        delete(this.sub)
      }
    })
  },
  balanceInlput(e) {
    this.setData({
      balance: e.detail.value
    })
  },
  phoneInlput(e) {
    this.setData({
      bind_phone: e.detail.value
    })
  },

  showModalInput(e) {
    const data = e.currentTarget.dataset;
    this.water_id = data.id;
    this.alterIndex = data.index;
    this.setData({
      isModalInput: true,
      showInput: true,
      balance: data.balance
    })
  },
  hideModalInput() {
    this.setData({
      isModalInput: false,
      balance: ""
    })
    setTimeout(() => {
      this.setData({
        showInput: false
      })
    }, 100)
    delete(this.water_id);
    delete(this.alterIndex)
  },
  showModalPhone(e) {
    const data = e.currentTarget.dataset;
    this.water_id = data.id;
    this.alterIndex = data.index;
    this.setData({
      isModalPhone: true,
      showPhone: true,
      bind_phone: data.bind_phone
    })
  },
  hideModalPhone() {
    this.setData({
      isModalPhone: false,
      bind_phone: ""
    })
    setTimeout(() => {
      this.setData({
        showPhone: false
      })
    }, 100)
    delete(this.water_id);
    delete(this.alterIndex)
  }
})